package com.sskj.hangqing.ui.fragment;


import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.sskj.common.adapter.slimadapter.IViewInjector;
import com.sskj.common.adapter.slimadapter.SlimAdapter;
import com.sskj.common.adapter.slimadapter.SlimInjector;
import com.sskj.common.base.App;
import com.sskj.common.rxbus2.RxBus;
import com.sskj.common.rxbus2.Subscribe;
import com.sskj.common.rxbus2.ThreadMode;
import com.sskj.depth.bean.DepthData;
import com.sskj.depth.bean.IDepthData;
import com.sskj.depth.view.DepthMapView;
import com.sskj.hangqing.R;
import com.sskj.hangqing.R2;
import com.sskj.hangqing.bean.rxbus.MarketCoinBean;
import com.sskj.hangqing.presenter.DeepthFragmentPresenter;
import com.sskj.lib.RConfig;
import com.sskj.lib.RxBusCode;
import com.sskj.lib.base.BaseFragment;
import com.sskj.lib.bean.WSFiveBean;
import com.sskj.lib.bean.enums.BuySellEnum;
import com.sskj.lib.box.LiveDataBus;
import com.sskj.lib.util.CoinUtil;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import io.reactivex.Flowable;

@Route(path = RConfig.HANG_FRAGMENT_DEEPTH)
public class DeepthFragment extends BaseFragment<DeepthFragmentPresenter> {
    private static final long MAX_NUM = 20;
    @Autowired
    String code;
    @Autowired
    String qu;
    @BindView(R2.id.tvBuyNumTitle)
    TextView tvBuyNumTitle;
    @BindView(R2.id.tvSellNumTitle)
    TextView tvSellNumTitle;
    @BindView(R2.id.recyclerViewBuy)
    RecyclerView buyRecyclerView;
    @BindView(R2.id.recyclerViewSell)
    RecyclerView sellRecyclerView;
    @BindView(R2.id.depthMapView)
    DepthMapView depthMapView;
    private SlimAdapter sellSlimAdapter;
    private SlimAdapter buySlimAdapter;

    @Override
    protected int getLayoutId() {
        return R.layout.hang_fragment_deepth;
    }

    @Override
    public DeepthFragmentPresenter getPresenter() {
        return new DeepthFragmentPresenter();
    }

    @Override
    public void initView() {
        ARouter.getInstance().inject(this);
        String replace = TextUtils.isEmpty(code.replace("_", "/")) ? "" : code.replace("_", "/");
        tvBuyNumTitle.setText(TextUtils.isEmpty(replace) ? "" : String.format(App.INSTANCE.getString(R.string.hangqingtradeFragment2), replace.substring(0, replace.indexOf("/"))));
        tvSellNumTitle.setText(TextUtils.isEmpty(replace) ? "" : String.format(App.INSTANCE.getString(R.string.hangqingtradeFragment2), replace.substring(0, replace.indexOf("/"))));
        initRecy();
//        depthMapView.setSelectBackgroundColor(ContextCompat.getColor(getActivity(), R.color.lib_bg));
//        depthMapView.setSelectTextColor(ContextCompat.getColor(getActivity(),R.color.libTextBlack));
        if (code.toUpperCase().contains("DIG")) {
            depthMapView.mPriceLimit = 6;
            depthMapView.mVolumeLimit = 6;
        } else {
            depthMapView.mPriceLimit = CoinUtil.getPriceKeepNum(code);
            depthMapView.mVolumeLimit = CoinUtil.getNumKeepNum(code);
        }
    }

    @Override
    public void initData() {
        mPresenter.getData(code);
        mPresenter.initSocket(code);
        LiveDataBus.get().with(RxBusCode.CHANGE_MARKET_CODE,MarketCoinBean.class)
                .observe(this,this::changeCoin);
    }

    private void initRecy() {
        sellRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        buyRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

        buySlimAdapter = SlimAdapter.create().register(R.layout.hang_recy_item_deep_buy, new SlimInjector<WSFiveBean.FiveBean>() {
            @Override
            public void onInject(WSFiveBean.FiveBean data, IViewInjector injector, List<Object> payloads) {
                injector.text(R.id.tvOrderNum, buySlimAdapter.getData().indexOf(data) + 1 + "")
                        .text(R.id.tvPrice, data.getPrice())
                        .textColor(R.id.tvPrice, ContextCompat.getColor(App.INSTANCE, BuySellEnum.BUY.getColorRes()))
                        .text(R.id.tvNum, data.getTotalSize())
                        .with(R.id.bibiProgressbar, view -> {
                            ProgressBar progressBar = (ProgressBar) view;
                            progressBar.setProgressDrawable(ContextCompat.getDrawable(App.INSTANCE, R.drawable.hang_progress_green));
                            progressBar.setProgress(100 - data.getPercent());
                        })
                ;
            }
        }).attachTo(buyRecyclerView).updateData(new ArrayList());
        sellSlimAdapter = SlimAdapter.create().register(R.layout.hang_recy_item_deep_sell, new SlimInjector<WSFiveBean.FiveBean>() {
            @Override
            public void onInject(WSFiveBean.FiveBean data, IViewInjector injector, List<Object> payloads) {
                injector.text(R.id.tvOrderNum, sellSlimAdapter.getData().indexOf(data) + 1 + "")
                        .textColor(R.id.tvPrice, ContextCompat.getColor(App.INSTANCE, BuySellEnum.SELL.getColorRes()))
                        .text(R.id.tvPrice, data.getPrice())
                        .text(R.id.tvNum, data.getTotalSize())
                        .with(R.id.bibiProgressbar, view -> {
                            ProgressBar progressBar = (ProgressBar) view;
                            progressBar.setProgressDrawable(ContextCompat.getDrawable(App.INSTANCE, R.drawable.hang_progress_red));
                            progressBar.setProgress(data.getPercent());
                        })
                ;
            }
        }).

                attachTo(sellRecyclerView).

                updateData(new ArrayList());
        sellRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                if (recyclerView.getScrollState() != RecyclerView.SCROLL_STATE_IDLE) {
                    buyRecyclerView.scrollBy(dx, dy);
                }
            }
        });
        buyRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                if (recyclerView.getScrollState() != RecyclerView.SCROLL_STATE_IDLE) {
                    sellRecyclerView.scrollBy(dx, dy);
                }
            }
        });
    }

    public void changeCoin(MarketCoinBean marketCoinBean) {
        code = marketCoinBean.getCode();
        qu = marketCoinBean.getQu();
        if (tvSellNumTitle == null)
            return;
        String replace = code.replace("_", "/");
        tvBuyNumTitle.setText(String.format(App.INSTANCE.getString(R.string.hangqingtradeFragment2), replace.substring(0, replace.indexOf("/")).toUpperCase()));
        tvSellNumTitle.setText(String.format(App.INSTANCE.getString(R.string.hangqingtradeFragment2), replace.substring(0, replace.indexOf("/")).toUpperCase()));
        mPresenter.getData(code);
        mPresenter.sendCode(code);
    }


    public void updateUI(WSFiveBean data) {
        if (data == null || buySlimAdapter == null)
            return;
        WSFiveBean wsFiveBean = new WSFiveBean();

        ArrayList<WSFiveBean.FiveBean> buyFiveBean = new ArrayList<>();
        ArrayList<WSFiveBean.FiveBean> sellFiveBean = new ArrayList<>();
        wsFiveBean.setCode(code);
        wsFiveBean.setBids(buyFiveBean);
        wsFiveBean.setAsks(sellFiveBean);
        Flowable.fromIterable(data.getBids())
                .take(MAX_NUM)
                .map(fiveBean -> buyFiveBean.add(new WSFiveBean.FiveBean(fiveBean.getDoubleTotalSize(), fiveBean.getPrice(), code)))
                .subscribe();
        Flowable.fromIterable(data.getAsks())
                .take(MAX_NUM)
                .map(fiveBean -> sellFiveBean.add(new WSFiveBean.FiveBean(fiveBean.getDoubleTotalSize(), fiveBean.getPrice(), code)))
                .subscribe();
        calculatePercentAll(wsFiveBean);
        buySlimAdapter.updateData(buyFiveBean);
        sellSlimAdapter.updateData(sellFiveBean);
        Collections.reverse(data.getAsks());
        Collections.reverse(data.getBids());
        Flowable<List<IDepthData>> buyFlow = Flowable.fromIterable(data.getBids())
                .map(fiveBean -> (IDepthData)new DepthData(fiveBean.getDoubleTotalSize()+"", fiveBean.getPrice()))
                .toList()
                .toFlowable();
        Flowable<List<IDepthData>> sellFlow = Flowable.fromIterable(data.getAsks())
                .map(fiveBean -> (IDepthData)new DepthData(fiveBean.getDoubleTotalSize()+"", fiveBean.getPrice()))
                .toList()
                .toFlowable();

        Flowable.zip(buyFlow, sellFlow, (buyData, sellData) -> {
            if (depthMapView == null) {
                return "0";
            }
            depthMapView.setData(buyData, sellData);
            return "1";
        }).subscribe();
    }

    private void calculatePercentAll(WSFiveBean wsFiveBean) {
        Double full = 0d;
        for (WSFiveBean.FiveBean bid : wsFiveBean.getBids()) {
            Double aDouble = Double.valueOf(bid.getDoubleTotalSize());
            if (aDouble > full) {
                full = aDouble;
            }
        }
        for (WSFiveBean.FiveBean ask : wsFiveBean.getAsks()) {
            Double aDouble = Double.valueOf(ask.getDoubleTotalSize());
            if (aDouble > full) {
                full = aDouble;
            }
        }
        for (WSFiveBean.FiveBean bid : wsFiveBean.getBids()) {
            Double aDouble = Double.valueOf(bid.getDoubleTotalSize());
            bid.setPercent((int) (aDouble / full * 100d));
        }

        for (WSFiveBean.FiveBean ask : wsFiveBean.getAsks()) {
            Double aDouble = Double.valueOf(ask.getDoubleTotalSize());
            ask.setPercent((int) (aDouble / full * 100d));
        }

    }

    @Override
    public void onDestroy() {
        mPresenter.closeWebSocket();
        super.onDestroy();
    }
}
